package com.southminority.ethnic.service.heritage.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.southminority.ethnic.common.exception.BusinessException;
import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.mapper.heritage.HeritageMapper;
import com.southminority.ethnic.mapper.heritage.InheritorMapper;
import com.southminority.ethnic.pojo.Heritage;
import com.southminority.ethnic.pojo.Inheritor;
import com.southminority.ethnic.service.heritage.HeritageService;
import com.southminority.ethnic.service.heritage.HeritageResearchLinkService;
import com.southminority.ethnic.controller.heritage.vo.HeritageVO;
import com.southminority.ethnic.controller.heritage.vo.HeritageResearchLinkVO;
import com.southminority.ethnic.controller.heritage.vo.InheritorVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 非物质文化遗产项目服务实现类.
 *
 * @author SouthMinority
 */
@Slf4j
@Service
public class HeritageServiceImpl implements HeritageService {

    private final HeritageMapper heritageMapper;
    private final InheritorMapper inheritorMapper;
    private final HeritageResearchLinkService researchLinkService;
    private final ObjectMapper objectMapper;

    public HeritageServiceImpl(HeritageMapper heritageMapper, 
                              InheritorMapper inheritorMapper,
                              HeritageResearchLinkService researchLinkService,
                              ObjectMapper objectMapper) {
        this.heritageMapper = heritageMapper;
        this.inheritorMapper = inheritorMapper;
        this.researchLinkService = researchLinkService;
        this.objectMapper = objectMapper;
    }

    // =================================================================================
    // ==                             前端展示相关方法 (Public API)                     ==
    // =================================================================================

    @Override
    public List<HeritageVO> getHeritageList() {
        // 构建查询条件：状态为已发布(1)，并按浏览量和创建时间降序排序
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByDesc("view_count")
               .orderByDesc("create_time");
        
        List<Heritage> heritageList = heritageMapper.selectList(wrapper);
        // 将POJO列表转换为VO列表
        return heritageList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<HeritageVO> getHeritageListByCondition(String heritageType, String level, 
                                                       String region, String ethnicGroup, 
                                                       String keyword, String sortBy, String sortOrder) {
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1); // 只查询已发布的
        
        // 动态构建筛选条件
        if (StringUtils.hasText(heritageType)) {
            wrapper.eq("heritage_type", heritageType);
        }
        if (StringUtils.hasText(level)) {
            wrapper.eq("level", level);
        }
        if (StringUtils.hasText(region)) {
            wrapper.like("region", region); // 地区使用模糊查询
        }
        if (StringUtils.hasText(ethnicGroup)) {
            wrapper.eq("ethnic_group", ethnicGroup);
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.and(qw -> qw.like("name", keyword)
                               .or().like("description", keyword)
                               .or().like("keywords", keyword));
        }
        
        // 动态构建排序条件
        if (StringUtils.hasText(sortBy)) {
            boolean isAsc = "asc".equalsIgnoreCase(sortOrder);
            // 为防止SQL注入，这里使用白名单方式校验排序字段
            switch (sortBy.toLowerCase()) {
                case "view_count":
                    wrapper.orderBy(true, isAsc, "view_count");
                    break;
                case "create_time":
                    wrapper.orderBy(true, isAsc, "create_time");
                    break;
                default:
                    // 默认排序
                    wrapper.orderByDesc("view_count").orderByDesc("create_time");
            }
        } else {
            // 默认排序
            wrapper.orderByDesc("view_count").orderByDesc("create_time");
        }
        
        List<Heritage> heritageList = heritageMapper.selectList(wrapper);
        return heritageList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public HeritageVO getHeritageDetail(Long id) {
        Heritage heritage = heritageMapper.selectById(id);
        if (heritage == null || heritage.getStatus() != 1) {
            throw new BusinessException("非遗项目不存在或已禁用");
        }
        
        HeritageVO vo = convertToVO(heritage);
        
        // 关联查询：获取该非遗项目下的传承人信息（只显示状态正常的）
        List<Inheritor> inheritors = inheritorMapper.selectByHeritageId(id);
        if (inheritors != null && !inheritors.isEmpty()) {
            List<InheritorVO> inheritorVOs = inheritors.stream()
                    .filter(inheritor -> inheritor.getStatus() == 1) // 过滤掉禁用的传承人
                    .map(this::convertInheritorToVO)
                    .collect(Collectors.toList());
            vo.setInheritors(inheritorVOs);
        }
        
        // 关联查询：获取相关的研究成果
        List<HeritageResearchLinkVO> researchLinks = researchLinkService.getResearchLinksByHeritageId(id);
        vo.setResearchLinks(researchLinks);
        
        // 注意：此处未增加浏览次数，如果需要在获取详情时增加，需要调用 increaseViewCount(id)
        return vo;
    }

    @Override
    @Transactional
    public Integer increaseViewCount(Long id) {
        Heritage heritage = heritageMapper.selectById(id);
        if (heritage == null) {
            throw new BusinessException("非遗项目不存在");
        }
        
        // 安全地增加浏览次数
        heritage.setViewCount((heritage.getViewCount() == null ? 0 : heritage.getViewCount()) + 1);
        heritageMapper.updateById(heritage);
        
        return heritage.getViewCount();
    }

    @Override
    public List<String> getHeritageTypes() {
        // 查询所有不重复的非遗类型，用于前端筛选菜单
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT heritage_type")
               .eq("status", 1)
               .isNotNull("heritage_type")
               .orderByAsc("heritage_type");
        
        List<Heritage> list = heritageMapper.selectList(wrapper);
        return list.stream()
                  .map(Heritage::getHeritageType)
                  .filter(StringUtils::hasText) // 过滤空字符串
                  .collect(Collectors.toList());
    }

    @Override
    public List<String> getLevels() {
        // 查询所有不重复的项目级别
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT level")
               .eq("status", 1)
               .isNotNull("level")
               .orderByAsc("level");
        
        List<Heritage> list = heritageMapper.selectList(wrapper);
        return list.stream()
                  .map(Heritage::getLevel)
                  .filter(StringUtils::hasText)
                  .collect(Collectors.toList());
    }

    @Override
    public List<String> getRegions() {
        // 查询所有不重复的地区
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT region")
               .eq("status", 1)
               .isNotNull("region")
               .orderByAsc("region");
        
        List<Heritage> list = heritageMapper.selectList(wrapper);
        return list.stream()
                  .map(Heritage::getRegion)
                  .filter(StringUtils::hasText)
                  .collect(Collectors.toList());
    }

    @Override
    public List<String> getEthnicGroups() {
        // 查询所有不重复的民族
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT ethnic_group")
               .eq("status", 1)
               .isNotNull("ethnic_group")
               .orderByAsc("ethnic_group");
        
        List<Heritage> list = heritageMapper.selectList(wrapper);
        return list.stream()
                  .map(Heritage::getEthnicGroup)
                  .filter(StringUtils::hasText)
                  .collect(Collectors.toList());
    }


    // =================================================================================
    // ==                             后台管理相关方法 (Admin API)                      ==
    // =================================================================================

    @Override
    public PageResult<HeritageVO> getHeritagePageForAdmin(Integer page, Integer size, 
                                                         String keyword, String heritageType, 
                                                         String level, Integer status) {
        Page<Heritage> pageObj = new Page<>(page, size);
        QueryWrapper<Heritage> wrapper = new QueryWrapper<>();
        
        // 动态构建查询和筛选条件
        if (StringUtils.hasText(keyword)) {
            wrapper.and(qw -> qw.like("name", keyword)
                               .or().like("description", keyword)
                               .or().like("keywords", keyword));
        }
        if (StringUtils.hasText(heritageType)) {
            wrapper.eq("heritage_type", heritageType);
        }
        if (StringUtils.hasText(level)) {
            wrapper.eq("level", level);
        }
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.ne("status", -1); // 管理端默认不显示已逻辑删除的
        }
        
        wrapper.orderByDesc("create_time");
        
        IPage<Heritage> pageResult = heritageMapper.selectPage(pageObj, wrapper);
        
        // 封装分页结果
        List<HeritageVO> voList = pageResult.getRecords().stream()
                                           .map(this::convertToVO)
                                           .collect(Collectors.toList());
        
        return PageResult.<HeritageVO>builder()
                .current(pageResult.getCurrent())
                .size(pageResult.getSize())
                .total(pageResult.getTotal())
                .pages(pageResult.getPages())
                .records(voList)
                .build();
    }

    @Override
    @Transactional
    public HeritageVO createHeritage(Heritage heritage) {
        if (heritage == null) {
            throw new BusinessException("非遗项目信息不能为空");
        }
        
        // 设置创建时的默认值
        if (heritage.getStatus() == null) heritage.setStatus(1); // 默认为已发布
        if (heritage.getViewCount() == null) heritage.setViewCount(0);
        
        int result = heritageMapper.insert(heritage);
        if (result <= 0) {
            throw new BusinessException("创建非遗项目失败");
        }
        
        return convertToVO(heritage);
    }

    @Override
    @Transactional
    public HeritageVO updateHeritage(Long id, Heritage heritage) {
        if (id == null || heritage == null) {
            throw new BusinessException("参数不能为空");
        }
        
        Heritage existingHeritage = heritageMapper.selectById(id);
        if (existingHeritage == null) {
            throw new BusinessException("非遗项目不存在");
        }
        
        // 调试日志：记录更新前的数据
        log.info("🔍 更新前的数据: title={}, approvalDate={}, mainFeatures={}", existingHeritage.getTitle(), existingHeritage.getApprovalDate(), existingHeritage.getMainFeatures());
        log.info("📥 接收到的更新数据: title={}, approvalDate={}, mainFeatures={}", heritage.getTitle(), heritage.getApprovalDate(), heritage.getMainFeatures());
        
        // 保护已下线的详细描述字段：如果前端不再提交这些字段，保持原值，避免被置空
        if (heritage.getHistoricalBackground() == null) heritage.setHistoricalBackground(existingHeritage.getHistoricalBackground());
        if (heritage.getCulturalValue() == null) heritage.setCulturalValue(existingHeritage.getCulturalValue());
        if (heritage.getCurrentStatus() == null) heritage.setCurrentStatus(existingHeritage.getCurrentStatus());
        if (heritage.getProtectionMeasures() == null) heritage.setProtectionMeasures(existingHeritage.getProtectionMeasures());
        if (heritage.getTransmissionMethods() == null) heritage.setTransmissionMethods(existingHeritage.getTransmissionMethods());
        if (heritage.getMainFeatures() == null) heritage.setMainFeatures(existingHeritage.getMainFeatures());
        if (heritage.getRelatedCustoms() == null) heritage.setRelatedCustoms(existingHeritage.getRelatedCustoms());
        // 批准日期为空时保持原值，避免被置空
        if (heritage.getApprovalDate() == null) heritage.setApprovalDate(existingHeritage.getApprovalDate());

        heritage.setId(id); // 保证ID正确
        heritage.setUpdateTime(LocalDateTime.now());
        
        // 调试日志：记录准备更新的完整数据
        log.info("💾 准备更新的数据: {}", heritage);
        
        int result = heritageMapper.updateById(heritage);
        log.info("🎯 更新操作结果: {}", result);
        
        if (result <= 0) {
            throw new BusinessException("更新非遗项目失败");
        }
        
        // 调试日志：查询更新后的数据验证
        Heritage updatedHeritage = heritageMapper.selectById(id);
        log.info("✅ 更新后的数据: title={}, mainFeatures={}", updatedHeritage.getTitle(), updatedHeritage.getMainFeatures());
        
        return convertToVO(updatedHeritage);
    }

    @Override
    @Transactional
    public Boolean deleteHeritage(Long id) {
        if (id == null) {
            throw new BusinessException("非遗项目ID不能为空");
        }
        
        Heritage heritage = heritageMapper.selectById(id);
        if (heritage == null) {
            throw new BusinessException("非遗项目不存在");
        }
        
        // 逻辑删除
        heritage.setStatus(-1);
        heritage.setUpdateTime(LocalDateTime.now());
        
        int result = heritageMapper.updateById(heritage);
        return result > 0;
    }

    @Override
    @Transactional
    public Boolean batchDeleteHeritage(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("删除的非遗项目ID列表不能为空");
        }
        
        List<Heritage> heritageList = heritageMapper.selectBatchIds(ids);
        if (heritageList.isEmpty()) {
            // 如果传入的ID都无效，也认为操作是成功的，或者可以抛出异常
            return true;
        }
        
        LocalDateTime now = LocalDateTime.now();
        for (Heritage heritage : heritageList) {
            heritage.setStatus(-1);
            heritage.setUpdateTime(now);
            heritageMapper.updateById(heritage);
        }
        
        return true;
    }

    @Override
    @Transactional
    public Boolean updateHeritageStatus(Long id, Integer status) {
        if (id == null || status == null) {
            throw new BusinessException("参数不能为空");
        }
        
        Heritage heritage = heritageMapper.selectById(id);
        if (heritage == null) {
            throw new BusinessException("非遗项目不存在");
        }
        
        heritage.setStatus(status);
        heritage.setUpdateTime(LocalDateTime.now());
        
        int result = heritageMapper.updateById(heritage);
        return result > 0;
    }

    @Override
    public HeritageVO getHeritageDetailForAdmin(Long id) {
        Heritage heritage = heritageMapper.selectById(id);
        if (heritage == null) {
            throw new BusinessException("非遗项目不存在");
        }
        
        HeritageVO vo = convertToVO(heritage);
        
        // 管理端查询传承人信息（包含所有状态，以便编辑）
        QueryWrapper<Inheritor> wrapper = new QueryWrapper<>();
        wrapper.eq("heritage_id", id);
        List<Inheritor> inheritors = inheritorMapper.selectList(wrapper);
        
        if (inheritors != null && !inheritors.isEmpty()) {
            List<InheritorVO> inheritorVOs = inheritors.stream()
                    .map(this::convertInheritorToVO)
                    .collect(Collectors.toList());
            vo.setInheritors(inheritorVOs);
        }
        
        return vo;
    }

    @Override
    @Transactional
    public Boolean createInheritor(Inheritor inheritor) {
        if (inheritor == null) {
            throw new BusinessException("传承人信息不能为空");
        }
        
        // 校验关联的非遗项目是否存在
        if (inheritor.getHeritageId() != null) {
            Heritage heritage = heritageMapper.selectById(inheritor.getHeritageId());
            if (heritage == null) {
                throw new BusinessException("关联的非遗项目不存在");
            }
        }
        
        if (inheritor.getStatus() == null) inheritor.setStatus(1); // 默认状态为正常
        
        int result = inheritorMapper.insert(inheritor);
        return result > 0;
    }

    @Override
    @Transactional
    public Boolean updateInheritor(Long id, Inheritor inheritor) {
        if (id == null || inheritor == null) {
            throw new BusinessException("参数不能为空");
        }
        
        Inheritor existingInheritor = inheritorMapper.selectById(id);
        if (existingInheritor == null) {
            throw new BusinessException("传承人不存在");
        }
        
        inheritor.setId(id);
        inheritor.setUpdateTime(LocalDateTime.now());
        
        int result = inheritorMapper.updateById(inheritor);
        return result > 0;
    }

    @Override
    @Transactional
    public Boolean deleteInheritor(Long id) {
        if (id == null) {
            throw new BusinessException("传承人ID不能为空");
        }
        
        Inheritor inheritor = inheritorMapper.selectById(id);
        if (inheritor == null) {
            throw new BusinessException("传承人不存在");
        }
        
        // 逻辑删除
        inheritor.setStatus(-1);
        inheritor.setUpdateTime(LocalDateTime.now());
        
        int result = inheritorMapper.updateById(inheritor);
        return result > 0;
    }

    @Override
    public List<Inheritor> getInheritorsByHeritageId(Long heritageId) {
        if (heritageId == null) {
            throw new BusinessException("非遗项目ID不能为空");
        }
        
        // 查询未被逻辑删除的传承人
        QueryWrapper<Inheritor> wrapper = new QueryWrapper<>();
        wrapper.eq("heritage_id", heritageId)
               .ne("status", -1)
               .orderByDesc("create_time");
        
        return inheritorMapper.selectList(wrapper);
    }

    @Override
    public PageResult<Inheritor> getInheritorPageForAdmin(Integer page, Integer size,
                                                          Long heritageId, String keyword, Integer status) {
        log.info("[SERVICE] InheritorPage params -> page={}, size={}, heritageId={}, keyword={}, status={}",
                page, size, heritageId, keyword, status);
        Page<Inheritor> pageObj = new Page<>(page, size);
        QueryWrapper<Inheritor> wrapper = new QueryWrapper<>();

        if (heritageId != null) {
            wrapper.eq("heritage_id", heritageId);
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.and(qw -> qw.like("name", keyword)
                    .or().like("ethnic_group", keyword)
                    .or().like("level", keyword)
                    .or().like("skills", keyword));
        }
        if (status != null) {
            wrapper.eq("status", status);
        } else {
            wrapper.ne("status", -1); // 默认排除删除
        }

        wrapper.orderByDesc("create_time");

        IPage<Inheritor> pageResult = inheritorMapper.selectPage(pageObj, wrapper);
        log.info("[SERVICE] InheritorPage result -> total={}, pages={}, current={}, size={}",
                pageResult.getTotal(), pageResult.getPages(), pageResult.getCurrent(), pageResult.getSize());
        return PageResult.<Inheritor>builder()
                .current(pageResult.getCurrent())
                .size(pageResult.getSize())
                .total(pageResult.getTotal())
                .pages(pageResult.getPages())
                .records(pageResult.getRecords())
                .build();
    }

    // =================================================================================
    // ==                             私有辅助方法 (Private Helpers)                      ==
    // =================================================================================

    /**
     * 将 Heritage POJO 转换为 HeritageVO DTO.
     * <p>
     * 此方法负责处理复杂数据类型的转换，例如将数据库中存储的JSON字符串或逗号分隔的字符串
     * 转换为Java的List，以便前端可以直接使用。
     *
     * @param heritage 数据库实体对象
     * @return 用于前端展示的视图对象
     */
    private HeritageVO convertToVO(Heritage heritage) {
        if (heritage == null) return null;
        HeritageVO vo = new HeritageVO();
        BeanUtils.copyProperties(heritage, vo);
        
        try {
            // 安全地反序列化JSON字符串为List
            if (StringUtils.hasText(heritage.getImageUrls())) {
                vo.setImages(objectMapper.readValue(heritage.getImageUrls(), new TypeReference<>() {}));
            }
            if (StringUtils.hasText(heritage.getVideoUrls())) {
                vo.setVideos(objectMapper.readValue(heritage.getVideoUrls(), new TypeReference<>() {}));
            }
            if (StringUtils.hasText(heritage.getAudioUrls())) {
                vo.setAudios(objectMapper.readValue(heritage.getAudioUrls(), new TypeReference<>() {}));
            }
            
            // 将逗号分隔的标签字符串转换为List
            if (StringUtils.hasText(heritage.getTags())) {
                vo.setTagList(Arrays.asList(heritage.getTags().split(",")));
            }
            
        } catch (Exception e) {
            log.error("非遗项目(ID:{})的JSON或标签字段转换失败: {}", heritage.getId(), e.getMessage());
        }
        
        return vo;
    }

    /**
     * 将 Inheritor POJO 转换为 InheritorVO DTO.
     * <p>
     * 主要处理字段名的映射，例如数据库中的 `biography` 字段映射为VO中的 `introduction`。
     *
     * @param inheritor 数据库实体对象
     * @return 用于前端展示的视图对象
     */
    private InheritorVO convertInheritorToVO(Inheritor inheritor) {
        if (inheritor == null) return null;
        InheritorVO vo = new InheritorVO();
        BeanUtils.copyProperties(inheritor, vo);
        
        // 字段名映射: biography -> introduction (因为POJO和VO字段名可能不一致)
        vo.setIntroduction(inheritor.getBiography());
        
        return vo;
    }
} 